package io.github.qifan777.server.rating.repository;

import io.github.qifan777.server.infrastructure.model.QueryRequest;
import io.github.qifan777.server.rating.entity.Rating;
import io.github.qifan777.server.rating.entity.RatingFetcher;
import io.github.qifan777.server.rating.entity.RatingTable;
import io.github.qifan777.server.rating.entity.dto.RatingSpec;
import io.github.qifan777.server.user.root.entity.UserFetcher;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.spring.repository.SpringOrders;
import org.babyfish.jimmer.spring.repository.support.SpringPageFactory;
import org.babyfish.jimmer.sql.fetcher.Fetcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface RatingRepository extends JRepository<Rating, String> {
    RatingTable t = RatingTable.$;
    RatingFetcher COMPLEX_FETCHER_FOR_ADMIN = RatingFetcher.$.allScalarFields()
        .creator(UserFetcher.$.phone().nickname())
        .editor(UserFetcher.$.phone().nickname());
    RatingFetcher COMPLEX_FETCHER_FOR_FRONT = RatingFetcher.$.allScalarFields()
            .creator(UserFetcher.$.phone().nickname().gender().avatar());
  default Page<Rating> findPage(QueryRequest<RatingSpec> queryRequest,
                                Fetcher<Rating> fetcher) {
    RatingSpec query = queryRequest.getQuery();
    Pageable pageable = queryRequest.toPageable();
    return sql().createQuery(t)
        .where(query)
        .orderBy(SpringOrders.toOrders(t, pageable.getSort()))
        .select(t.fetch(fetcher))
        .fetchPage(queryRequest.getPageNum() - 1, queryRequest.getPageSize(),
            SpringPageFactory.getInstance());
  }
}